﻿///***************************************************************
/// 시  스  템 : Updms.Crd
/// 단위시스템 : CRD
/// 계      층 : Presentation Layer
/// 프로그램명 : Crd3013p
/// 파  일  명 : Crd3013p.aspx.cs
/// 설      명 : 월간사용분석표(연간사용분석표에서 X월 클릭시 팝업)
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2010-07-19 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Adapter;
using SMFramework.Data;
using SMFramework.Security;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Common.BaseClass;
using Updms.Crd.Exe;


namespace Updms.Crd
{
	public partial class Crd3013p : Updms.Common.BaseClass.PageBase
    {
        #region 전역영역

		//프로그램상수
		public static readonly string PID = "Crd3013p";
		public static readonly string gs_path_info = "/updms/Crd/" + PID + ".aspx";

		Global global = new Global();
		Crypto crypto = new Crypto();
      
		//검색
		protected string kw1 = "";	//카드코드
		protected string kw2 = "";	//기준년월
		protected string gs_card_nm = "";	//카드명

		//합계
		decimal ld_pre_total = 0;
		decimal ld_this_total = 0;
		decimal ld_diff_total = 0;

        #endregion

        #region Page_Load, OnPageLoad

        protected void Page_Load(object sender, EventArgs e)
        {
            SetInit();
            if (!Page.IsPostBack)
            {
                // 최초 화면 로딩시 처리해야 할 부분
                OnPageLoad();
                SearchProcess();
            }
        }

        // OnPageLoad
        private void OnPageLoad()
        {
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
            SetSearchParameter();
        }

        #endregion

        #region InitializeComponent

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
            this.PreRender += new System.EventHandler(this.Page_PreRender);
        }

        #endregion       

        #region SetInit, SetSearchParameter, ShowKeywordLabel

        //초기값설정
        private void SetInit()
        {
        
        }

        //검색파라미터
        private void SetSearchParameter()
        {
            if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
            {
                kw1 = "CC01X";
            }
            else
            {
                kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
            }
            if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
            {
                kw2 = DateUtil.GetNow("yyyy-MM");
            }
            else
            {
                kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
            }
			if (String.IsNullOrEmpty(Request.QueryString["gs_card_nm"]))	// url에 값이 없으면
			{
				gs_card_nm = "비씨 마이원";
			}
			else
			{
				gs_card_nm = Server.UrlDecode(Request.QueryString["gs_card_nm"]);
			}
        }

        #endregion 

		#region 디테일 Method (CreateFileReal)

		//실제파일생성
		private void CreateFileReal(string ls_file_nm, DataSet ds)
		{
			try
			{
				int preTotalTemp = 0;
				int thisTotalTemp = 0;
				int diffTotalTemp = 0;

				string tableName = "UPDMS_CRD_REPORT";
				string ls_stream = FILE_PATH_FTP_UPLOAD + "\\" + ls_file_nm;
				FileInfo file = new FileInfo(ls_stream);

				StreamWriter sw = file.CreateText();

				sw.WriteLine(CommUtil.GetDefaultHtmlTag(PID, global.GetMenuTitle(PID, LANG_SET) + "(" + kw2 + ")"));
				sw.WriteLine("<table class=\"report\">");
				sw.WriteLine("<tr>");
				sw.WriteLine("<th>계정</th>");
				sw.WriteLine("<th>전월</th>");
				sw.WriteLine("<th>당월</th>");
				sw.WriteLine("<th>증감액</th>");
				sw.WriteLine("</tr>");
				for (int i = 0; i < DataSetUtil.GetRowCount(ds, tableName); i++)
				{
					string accountNm = DataSetUtil.GetFldStr(ds, tableName, i, "Account_Nm");
					int preTotal = DataSetUtil.GetFldInt(ds, tableName, i, "Pre_Total");
					int thisTotal = DataSetUtil.GetFldInt(ds, tableName, i, "This_Total");
					int diffTotal = DataSetUtil.GetFldInt(ds, tableName, i, "Diff_Total");

					preTotalTemp += preTotal;
					thisTotalTemp += thisTotal;
					diffTotalTemp += diffTotal;

					sw.WriteLine("<td class=\"lbl\">" + accountNm + "</td>");
					sw.WriteLine("<td class=\"data\">" + preTotal.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + thisTotal.ToString("#,###,##0") + "</td>");
					sw.WriteLine("<td class=\"data\">" + diffTotal.ToString("#,###,##0") + "</td>");
					sw.WriteLine("</tr>");
				}
				//총계
				sw.WriteLine("<tr class=\"total\">");
				sw.WriteLine("<td class=\"lbl\">총계</td>");
				sw.WriteLine("<td class=\"data\">" + preTotalTemp.ToString("#,###,##0") + "</td>");
				sw.WriteLine("<td class=\"data\">" + thisTotalTemp.ToString("#,###,##0") + "</td>");
				sw.WriteLine("<td class=\"data\">" + diffTotalTemp.ToString("#,###,##0") + "</td>");
				sw.WriteLine("</tr>");
				sw.WriteLine("</table>");
				sw.WriteLine("</body>");
				sw.WriteLine("</html>");

				sw.Close();
			}
			catch (Exception e)
			{
				Base.AppFramework.SMEventLog.WriteExceptionLog(e);
				CallMsgBoxInAjax("MSG_ERR_122");	//파일을 생성하지 못했습니다
			}
		}

		#endregion

		#region CRUD (GetMonthlyAmountByCardNAccount, GetIncDecAmountByAccountFromPreMonth, SearchProcess)

		#region 카드별 총액
		
		//카드별 총액
		private void GetMonthlyAmountByCardNAccount()
        {
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_card_nm", typeof(string), gs_card_nm);
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "false");

			using (Crd3013p_NT _Crd3013p_NT = new Crd3013p_NT())
			{
				lo_ds.Merge(_Crd3013p_NT.GetMonthlyAmountByCardNAccount(lo_dp));

				if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CRD_REPORT"))
				{
					GridView1.DataSource = lo_ds;
					GridView1.DataBind();

					GridView1_nodata.Visible = false;
				}
				else
				{
					GridView1_nodata.Visible = true;
				}
				ViewChart(lo_ds);
			}
        }
        
        #endregion

		#region 계정별 전월대비 증감액

		//계정별 전월대비 증감액
		private void GetIncDecAmountByAccountFromPreMonth()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_pre_month", typeof(string), DateUtil.GetCalcMonth(kw2, -1, "yyyy-MM"));
			lo_dp.AddProperty("ls_this_month", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Crd3013p_NT _Crd3013p_NT = new Crd3013p_NT())
			{
				lo_ds.Merge(_Crd3013p_NT.GetIncDecAmountByAccountFromPreMonth(lo_dp));

				GridView2.DataSource = lo_ds;
				GridView2.DataBind();

				ViewIncDecChart(lo_ds);
			}
		}

		#endregion

		#region 카드별분포도

		//카드별분포도
        private void ViewChart(DataSet po_ds)
        {
			int li_count = DataSetUtil.GetRowCount(po_ds, "UPDMS_CRD_REPORT");

			if (li_count > 0)
			{
				//초기화
				chart_pie_detail.Data.Clear();
				
				string[] ls_card_nm = gs_card_nm.Split(',');

				for (int i = 0; i < ls_card_nm.Length; i++)
				{
					//수동으로 데이터 바인딩
					chart_pie_detail.Data[0, i]
						= Convert.ToInt32(ConversionUtil.RemoveComma(DataSetUtil.GetFldStr(po_ds, "UPDMS_CRD_REPORT", po_ds.Tables["UPDMS_CRD_REPORT"].Rows.Count - 1, ls_card_nm[i].ToString())));

					//X축 라벨링
					chart_pie_detail.AxisX.Labels[i] = ls_card_nm[i].ToString();
				}
			}
			else
			{
				chart_pie_detail.Visible = false;
			}
		}

		#endregion

		#region 증가(감소)계정분포도

		//증가(감소)계정분포도
		private void ViewIncDecChart(DataSet po_ds)
		{
			int li_count = DataSetUtil.GetRowCount(po_ds, "UPDMS_CRD_REPORT");
			
			if (li_count > 0)
			{
				//초기화
				chart_inc_pie.Data.Clear();
				chart_dec_pie.Data.Clear();

				for (int i = 0; i < li_count; i++)
				{
					int li_amount = Convert.ToInt32(ConversionUtil.RemoveComma(DataSetUtil.GetFldStr(po_ds, "UPDMS_CRD_REPORT", i, "Diff_Total")));
					string ls_account = DataSetUtil.GetFldStr(po_ds, "UPDMS_CRD_REPORT", i, "Account_Nm");
					if (li_amount > 0)
					{
						chart_inc_pie.Data[0, i] = li_amount;
						chart_inc_pie.AxisX.Labels[i] = ls_account;
					}
					else if (li_amount < 0)
					{
						chart_dec_pie.Data[0, i] = li_amount;
						chart_dec_pie.AxisX.Labels[i] = ls_account;
					}
				}
			}
			else
			{
				chart_inc_pie.Visible = false;
				chart_dec_pie.Visible = false;
			}
		}

		#endregion

		//검색
        private void SearchProcess()
        {
            SetSearchParameter();
			GetMonthlyAmountByCardNAccount();
			GetIncDecAmountByAccountFromPreMonth();
        }

        #endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

        #endregion

        #region GridView이벤트

        //RowDataBound
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
			GridView gv = (GridView)sender;

			e.Row.Cells[0].Visible = false;	//View_Order 숨기기
			
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Left;
				
				//금액부분은 오른쪽 정렬
				for (int i = 2; i < e.Row.Cells.Count; i++)
				{
					e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Right;
				}

				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "BB006": //총계
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					default:
						break;
				}
			}
	    }
        
        //RowDataBound
        protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
        {
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//증감
				if (e.Row.Cells[5].Text.Substring(0, 1) == "-")
				{
					e.Row.Cells[5].Attributes.Add("class", "color_blue");
				}
				else
				{
					e.Row.Cells[5].Attributes.Add("class", "color_darkred");
				}

				//페이지별 합계
				ld_pre_total += Convert.ToDecimal(GridView2.DataKeys[e.Row.RowIndex].Values["Pre_Total"].ToString());
				ld_this_total += Convert.ToDecimal(GridView2.DataKeys[e.Row.RowIndex].Values["This_Total"].ToString());
				ld_diff_total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Diff_Total"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Attributes.Add("class", "total_v3");
				e.Row.Cells[0].Text = "Total";
				e.Row.Cells[0].Attributes.Add("class", "t_left div_line_tb_dbl");
				e.Row.Cells[2].Text = ld_pre_total.ToString("#,###,##0");
				e.Row.Cells[2].Attributes.Add("class", "money div_line_tb_dbl");
				e.Row.Cells[4].Text = ld_this_total.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money div_line_tb_dbl");
				e.Row.Cells[5].Text = ld_diff_total.ToString("#,###,##0");
				e.Row.Cells[5].Attributes.Add("class", "money div_line_tb_dbl");
			}
        }

        #endregion

        #region 버튼이벤트

        //검색
        protected void ibtn_search_Click(object sender, EventArgs e)
        {
            SearchProcess();
        }

		//카드별 총액 엑셀
        protected void ibtn_excel1_Click(object sender, EventArgs e)
        {
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_card_nm", typeof(string), gs_card_nm);
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "true");

			using (Crd3013p_NT _Crd3013p_NT = new Crd3013p_NT())
			{
				lo_ds.Merge(_Crd3013p_NT.GetMonthlyAmountByCardNAccount(lo_dp));
			}

			//컬럼수만큼의 크기를 갖는 배열을 생성
			string[] columns = gs_card_nm.Split(',');
			string[] headerTexts = new string[columns.Length + 2]; // +2(Account_Nm, Total)

			headerTexts[0] = "Account_Nm^" + global.GetLabelNmBySeq(55, LANG_SET); //계정

			for (int i = 1; i < headerTexts.Length - 1; i++)
			{
				headerTexts[i] = columns[i - 1] + "^" + columns[i - 1];
			}

			headerTexts[headerTexts.Length - 1] = "Total^Total";

			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + "-카드별_총액)";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, headerTexts);
        }

		//계정별 전월대비 증감액 엑셀
		protected void ibtn_excel2_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
			lo_dp.AddProperty("ls_pre_month", typeof(string), DateUtil.GetCalcMonth(kw2, -1, "yyyy-MM"));
			lo_dp.AddProperty("ls_this_month", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Crd3013p_NT _Crd3013p_NT = new Crd3013p_NT())
			{
				lo_ds.Merge(_Crd3013p_NT.GetIncDecAmountByAccountFromPreMonth(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + "-계정별_전월대비_증감액)";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET), "Excel2"));
		}

		//FTP
		protected void ibtn_ftp_Click(object sender, EventArgs e)
		{
			string fileName = PID + ".html";
			FtpClient fc = new FtpClient(FTP_HOSTNAME, FTP_USERID, crypto.Decrypt(FTP_PASSWORD));

			try
			{
				SetSearchParameter();

				DataSet lo_ds = new DataSet();
				DataPack lo_dp = new DataPack();

				lo_dp.AddProperty("ls_card_cd", typeof(string), kw1);
				lo_dp.AddProperty("ls_pre_month", typeof(string), DateUtil.GetCalcMonth(kw2, -1, "yyyy-MM"));
				lo_dp.AddProperty("ls_this_month", typeof(string), kw2);
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

				using (Crd3013p_NT _Crd3013p_NT = new Crd3013p_NT())
				{
					lo_ds.Merge(_Crd3013p_NT.GetIncDecAmountByAccountFromPreMonth(lo_dp));
				}

				//파일생성
				CreateFileReal(fileName, lo_ds);

				//FTP전송
				if (FileUtil.IsFileExist(FILE_PATH_FTP_UPLOAD + "\\" + fileName))
				{
					fc.Login();
					fc.BinaryMode = false;

					string[] remoteDir = StringUtil.DelimitedListToStringArray(FTP_DIR_IPHONE_CRD, "/");
					for (int i = 0; i < remoteDir.Length; i++)
					{
						fc.ChangeDir(remoteDir[i]);
					}

					if (fc.IsFileExist(fileName))
					{
						fc.DeleteFile(fileName);
					}

					fc.UploadOnlyFile(FILE_PATH_FTP_UPLOAD, fileName, "", "", true);
					fc.Close();
				}
				else
				{
					CallMsgBoxInAjax("MSG_ERR_164");	//전송할 파일이 없습니다.
				}
				CallMsgBoxInAjax("MSG_INF_018");	//전송되었습니다
			}
			catch (Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}
			finally
			{
				fc.Close();
			}
		}


        #endregion


    }
}
